import html, { makeHtmlAttributes } from "@rollup/plugin-html";
import livereload from "rollup-plugin-livereload";
import serve from "rollup-plugin-serve";
import resolve, { nodeResolve } from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import babel from "@rollup/plugin-babel";

// loader

export default {
  input: "src/index.js",
  output: {
    dir: "dist",
    format: "iife",
    sourceMap: "inline"
  },
  plugins: [
    // resolve({ extensions, preferBuiltins: true }),
    // nodeResolve(),
    // babel({
    //   // exclude: "node_modules/**",
    //   runtimeHelpers: true
    // }),
    // babel({
    //   // extensions,
    //   babelHelpers: "bundled",
    //   exclude: ["node_modules/**"]
    // }),
    // commonjs(),
    html({
      title: "Nirvana 测试",
      meta: [
        { charset: "utf-8" },
        { name: "viewport", content: "minimum-scale=1, initial-scale=1, width=device-width" }
      ],
      template: ({ attributes, bundle, files, meta, publicPath, title }) => {
        // return `fff`
        const scripts = (files.js || [])
          .map(({ fileName }) => {
            const attrs = makeHtmlAttributes(attributes.script);
            return `<script src="${publicPath}${fileName}"${attrs}></script>`;
          })
          .join("\n");

        const links = (files.css || [])
          .map(({ fileName }) => {
            const attrs = makeHtmlAttributes(attributes.link);
            return `<link href="${publicPath}${fileName}" rel="stylesheet"${attrs}>`;
          })
          .join("\n");

        const metas = meta
          .map((input) => {
            const attrs = makeHtmlAttributes(input);
            return `<meta${attrs}>`;
          })
          .join("\n");

        return `<!DOCTYPE html>
          <html>
            <head>
              ${metas}
              <title>${title}</title>
              ${links}
            </head>
            <body>
              <canvas id="engine-nirvana"></canvas>
              ${scripts}
            </body>
          </html>`;
      }
    }),
    serve({
      // open: true,
      openPage: "/dist/index.html",
      port: 10001
    }),
    livereload()
  ]
}